<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );

class JAJobBoardModelJAXMLImport extends JModel
{
	var $_id;
	var $_db;
	var $_data;
    var $_table;
    var $_pagination;
    
    /**
    * Return the query is used to retrive all row from database
    * @return string The query is used 
    */
    function getItems($catid=0){
    	global $mainframe;    	    	
    	
    	$db = & JFactory::getDBO();
    	
    	$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit',		'limit',		$mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( JBCOMNAME.'.jaxmlimport.limitstart',	'limitstart',	0, 'int' );
        
        $filter_order = JRequest::getVar('filter_order', 'u.FeedID');
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( JBCOMNAME .".jaxmlimport.filter_order_Dir",	'filter_order_Dir',	'DESC',			'word' );
        				
        // just in case filter_order get's messed up
       
		if ($filter_order) {
			$orderby = ' ORDER BY '.$filter_order .' '. $filter_order_Dir;
		} else {
			$orderby = ' ORDER BY u.FeedID DESC';
		}
		
        $query = "SELECT u.* ".
        		"\n FROM #__ja_xml_import_feeds u ".
        		$orderby;
		$db = &JFactory::getDBO();
		$db->setQuery($query);	
		$items = $db->loadObjectList();
		
		$total = count( $items );
		jimport('joomla.html.pagination');
		$this->_pagination = new JPagination( $total, $limitstart, $limit );
		
		$list = array();
		// slice out elements based on limits
		if($items)
			$list = array_slice( $items, $this->_pagination->limitstart, $this->_pagination->limit );
		
		return $list;
    }
    
    /**
    * Return the query is used to retrive all row from database
    * @return string The query is used 
    */
    function getImported(){
    	global $mainframe;    	    	
    	
    	$db = & JFactory::getDBO();
    	
    	$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit',		'limit',		$mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( JBCOMNAME.'.jaxmlimport.limitstart',	'limitstart',	0, 'int' );
       
        $filter_order = JRequest::getVar('filter_order', 'u.id');
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( JBCOMNAME .".jaxmlimport.filter_order_Dir",	'filter_order_Dir',	'DESC',			'word' );
        $search				= $mainframe->getUserStateFromRequest( JBCOMNAME .".jaxmlimport.search",			'search',			'',				'string' );
		$search				= JString::strtolower( $search );
		
		$usertype = '';
		$usertype			= $mainframe->getUserStateFromRequest( JBCOMNAME.'.jaxmlimport.usertype', 'usertype', '',	'string' );
					
		$where = null;

		if($search){
			$where[] = " (u.title LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false )." or u.job_detail LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false ).")";			
		}
		
		if($usertype){
			$where[] = " u.feed_id = '{$usertype}' ";			
		}
				
        // just in case filter_order get's messed up
       
		if ($filter_order) {
			$orderby = ' ORDER BY '.$filter_order .' '. $filter_order_Dir;
		} else {
			$orderby = ' ORDER BY u.id DESC';
		}
        
		if($where)
        	$where = "\n WHERE u.feed_id > 0  AND ". implode(' and ', $where);
        else 
        	$where = "\n WHERE u.feed_id > 0 ";
		       
        $query = "SELECT u.*, (SELECT FeedName FROM #__ja_xml_import_feeds WHERE u.feed_id = #__ja_xml_import_feeds.FeedID) as FeedName, ".
        		"\n (SELECT text FROM #__ja_codes WHERE u.status = #__ja_codes.value AND #__ja_codes.field_id = 'ja_jobs_status') as status_name ".
        		"\n FROM #__ja_jobs u ".
        		$where.
        		$orderby;
		$db = &JFactory::getDBO();
		$db->setQuery($query);	
		$items = $db->loadObjectList();
		
		$total = count( $items );

		jimport('joomla.html.pagination');
		$this->_pagination = new JPagination( $total, $limitstart, $limit );
		
		$list = array();
		// slice out elements based on limits
		if($items)
			$list = array_slice( $items, $this->_pagination->limitstart, $this->_pagination->limit );
		
		return $list;
    }
    
    /**
	* Get page navigator object
	* @return 
	*/
	function &getPagination(){
		if ($this->_pagination == null) {
			$this->getItems();
		}
		return $this->_pagination;
	}
	
	/**
	 * Method to store a record
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function storeCategory()
	{
		$row =& $this->getTable("ja_feeds_categories","JobBoardTable");
		$data = JRequest::get( 'post' );

		// Bind the form fields to the hello table
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		// Make sure the hello record is valid
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		// Store the web link table to the database
		if (!$row->store()) {
			$this->setError( $row->getErrorMsg() );
			return false;
		}

		return true;
	}

	/**
	 * Method to delete record(s)
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function deleteCategory()
	{
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		$row =& $this->getTable("ja_feeds_categories","JobBoardTable");

		if (count( $cids )) {
			foreach($cids as $cid) {
				if (!$row->delete( $cid )) {
					$this->setError( $row->getErrorMsg() );
					return false;
				}
			}
		}
		return true;
	}
	
	// Load feed row to array
	
	function fcnLoadFeedRow($feedID) {
		$db =& JFactory::getDBO();
		$sql = "SELECT * FROM #__ja_xml_import_feeds WHERE FeedID = '".($feedID)."'";
		
		$db->setQuery($sql);
		$row = $db->loadAssoc();
							
		if ($row['FeedMetaData'] != '') {
			$row['FMD'] = unserialize($row['FeedMetaData']);
		} else {
			$row['FMD'] = new clsMetaData($feedID);		
		}
		$row['FeedMetaData'] = '';
		
		return $row;	
	}
	
	/*
	 * Load the feed data in to an array
	 */
	function fcnLoadFeedRowDatas($feedID) {
		$db =& JFactory::getDBO();
		$sql = "SELECT * FROM #__ja_xml_import_feeds WHERE FeedID='".($feedID)."'";
		$db->setQuery($sql);
		$row = $db->loadAssoc();
		
		if ($row['FeedMetaData'] != '') {
			$row['FMD'] = unserialize($row['FeedMetaData']);
		} else {
			$row['FMD'] = new clsMetaData($feedID);
		}
		//$row['feed_metadata'] = '';
		
		return $row;	
	}
	
	/**
	 * Method to store XML structure
	 * @access	public
	 * @return	boolean	True on success
	 */
	function storeStruct($element, $feedID=0){
		$feed = $this->fcnLoadFeedRow($feedID);
		
		// Check last sequence element
		if( $feed['FMD']->seq != $element && !empty($feed['FMD']->seq)){
			$db =& JFactory::getDBO();
			$sql = "UPDATE #__ja_xml_import_feeds SET Status = 'NEW_SAMPLE' WHERE FeedID ='".$feedID."'";
			$db->setQuery($sql);
			$db->query();
		}
		
		$feed['FMD']->setSequenceElement($element);
		$feed['FMD']->FeedID = $feed['FeedID'];
		$feed['FMD']->save();
		
		return true;
	}
	
	/**
	 * Method to store map field
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function storeField( $feedID=0){
		
		$feedID = (int) $_REQUEST['FeedID'];

		$feed = $this->fcnLoadFeedRow($feedID);
		
		$feed['FMD']->fcnFillOptions();
		$feed['FMD']->feed_id = $feed['FeedID'];
		$feed['FMD']->save();
				
		return true;
	}
	
	/**
	 * Method to store a record
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function storeItem()
	{
		$row =& $this->getTable("ja_xml_import_feeds","JobBoardTable");
		$data = JRequest::get( 'post' );
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
		$cids = $cids[0];
		
		$feedID = (int) JRequest::getVar("FeedID");
		// Proccess data...
		if ($_FILES['xml_sample']['name']!='') {		
			// Get extesions
			$path_info = pathinfo($_FILES['xml_sample']['name']);
			if($path_info['extension'] != 'xml'){
				$this->setRedirect("index.php?option=com_jajobboard&view=jaxmlimport&tab=feeds&task=edit&cid[]=".$cids, JText::_("Invalid XML sample file extension. Allow *.xml extension files only!"));
			}
			
			// Create xml_export directory in: site/components/com_jajobboard/uploads/
			jimport('joomla.filesystem.folder');
			jimport('joomla.filesystem.file');
			
			global $jbconfig;
			
			$dir = JPATH_SITE.$jbconfig['general']->get('upload_folder', DS.'images'.DS.'stories'.DS.'jbuploads');
			$dir = $dir.DS."xml_import";
			if(!JFolder::exists($dir)){
				JFolder::create($dir, 777);
			}
			
			$uploaddir = $dir.DS;
	
			$a = explode(".",$_FILES['xml_sample']['name']);
			$ext = strtolower(array_pop($a));
			$name = strtolower(array_shift($a));
			
			$name = "xml_".$name;			
		   
			$name = preg_replace('#[^a-z^0-9]+#i', "_", $name); // strip out unwanted characters
			$ext = preg_replace('#[^a-z^0-9]+#i', "_", $ext); // strip out unwanted characters
			
			$new_name = $name.time().".".$ext;
			$uploadfile = $uploaddir.DS. $new_name; //
	
			if (strpos(strtoupper(PHP_OS), 'WIN') !== false) { 
				// sometimes the dir can have double slashes on Win, remove 'em
				$_FILES['xml_sample']['tmp_name'] = str_replace ('\\\\', '\\', $_FILES['xml_sample']['tmp_name']);
			}
			
			if (JFile::upload($_FILES['xml_sample']['tmp_name'], $uploadfile)) {
				//echo "File is valid, and was successfully uploaded.\n";
				@chmod ($uploadfile, 0666);
			}
			
			$fp = fopen($uploadfile, 'r');
			$xml_sample = fread($fp, filesize($uploadfile));
			$data['SampleString'] = $xml_sample;
			$data['Status'] = "NEW_SAMPLE";
			fclose($fp);
			
			// unlink($dir); // do not need it anymore
			
			if ($feedID != false) {
				// reset the sequence element.
				$feed_row = $this->fcnLoadFeedRow($feedID);
				$feed_row['FMD']->seq = '';
				$feed_row['FMD']->save();
				$data['Status'] = $this->fcnUpdateXMLImportStatus($feed_row);			
				
				$data['FeedMetaData'] = serialize(new clsMetaData($feedID));
			}			
		}	
		
		// Bind the form fields to the hello table
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());			
			return false;
		}
		
		// Make sure the hello record is valid
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		// Store the web link table to the database
		if (!$row->store()) {
			$this->setError( $row->getError() );
			return false;
		}
		
		return true;
	}
	
	/**
	 * Check valid condition for import data
	 * @return string $error Error message
	 * */
	
	function fcnValidateFieldSetupForm() {
		
		$error = "";
		
		if ((JRequest::getVar('account_create')=='ONLY_DEFAULT') || (JRequest::getVar('account_create')=='IMPORT_DEFAULT')) {
			if (trim(JRequest::getVar('default_user'))==false) {
				$error .= "- Please specify a valid default username<br>";
			}
		}
		
		if (JRequest::getVar('account_create') != 'ONLY_DEFAULT') {
			
			if (JRequest::getVar('ac_Username')==false) {
				$error .= "- Account details: Please select the field from which to import the usernames from<br>";
			}
			/*if (JRequest::getVar('ac_Password')==false) {
				$error .= "- Account details: Please select the field from which to import the passwords from<br>";
			}*/
			if (JRequest::getVar('ac_Email')==false) {
				$error .= "- Account details: Please select the field from which to import the emails from<br>";
			}
			if (JRequest::getVar('ac_FirstName')==false) {
				$error .= "- Account details: Please select the field from which to import the first names from<br>";
			}	
		}
		
		return $error;
		
	}
	
	/**
	 * Update status for each record
	 * @param array $feed_row Feed data
	 * @return string $status Status of import data
	 * */
	
	function fcnUpdateXMLImportStatus(&$feed_row) {

		$status = $feed_row['Status'];
		
		if (!isset($feed_row['FMD'])) {
			if ($feed_row['FeedMetaData']!='') {
				$feed_row['FMD'] = unserialize($feed_row['FeedMetaData']);
			} else {
				return 'NEW_SAMPLE';
			}
		}
		
		switch ($status) {
			
			case 'NEW_SAMPLE':
				if ($feed_row['FMD']->seq != false) {
					$status = 'SET_FIELDS';
				}
				
				break;
			case 'SET_FIELDS':
				if ($feed_row['FMD']->seq != false) {
					$feed_row['FMD']->fcnFillRequest();
					$error = "YES";
					if($feed_row['FMD']->options){	
						$parser = new xmlFeedFieldParser($feed_row['SampleString']);
						foreach($parser->data as $k=>$v){
							if (strpos($k, $feed_row['FMD']->seq)!==false) {
							if(trim($feed_row['FMD']->options['job_identifier']) == trim($k)){
								$error = JAJobBoardModelJAXMLImport::fcnValidateFieldSetupForm();
							}
							}
						}							
					}
					if ($error=='') {
						$status = "READY";
					}
				} else {
					$status = 'NEW_SAMPLE';
				}
				break;
	
			case 'READY':
				if ($feed_row['FMD']->seq != false) {
					$feed_row['FMD']->fcnFillRequest();
					$error = JAJobBoardModelJAXMLImport::fcnValidateFieldSetupForm();
					if ($error!='') {
						$status = "SET_FIELDS";
					}
				} else {
					$status = 'NEW_SAMPLE';
				}
				break;
			case 'DONE':
				if ($feed_row['FMD']->seq != false) {
					$feed_row['FMD']->fcnFillRequest();
					$error = JAJobBoardModelJAXMLImport::fcnValidateFieldSetupForm();
					if ($error!='') {
						$status = "SET_FIELDS";
					}
				} else {
					$status = 'NEW_SAMPLE';
				}
				break;
		}
		$db =& JFactory::getDBO();
		$sql = "UPDATE #__ja_xml_import_feeds SET Status='".$status."' WHERE FeedID='".$feed_row['FeedID']."' ";
		
		$db->setQuery($sql);
		$db->query();
		
		return $status;
	}
	
	/**
	 * Method to delete record(s)
	 * @access	public
	 * @return	boolean	True on success
	 */
	function deleteItems()
	{
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		$row =& $this->getTable("ja_xml_import_feeds","JobBoardTable");

		if (count( $cids )) {
			foreach($cids as $cid) {
				if (!$row->delete( $cid )) {
					$this->setError( $row->getError() );
					return false;
				}
			}
		}
		return true;
	}
	
	/**
	 * Method to get a hello
	 * @return object with data
	 */
	function getCategoryItem()
	{
		$this->_id = JRequest::getVar('cid',  0, '', 'array');
		$this->_id = (int) $this->_id[0];
		// Load the data
		if (empty( $this->_data )) {
			$query = ' SELECT * FROM #__ja_feeds_categories'.
					'  WHERE id = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();
		}
		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->id = 0;
			$this->_data->title = null;
			$this->_data->description = null;
			$this->_data->published = null;
		}
		return $this->_data;
	}
	
	/**
	 * Method to get a hello
	 * @return object with data
	 */
	function getFeedItem()
	{
		$this->_id = JRequest::getVar('cid',  0, '', 'array');
		$this->_id = (int) $this->_id[0];
		// Load the data
		if (empty( $this->_data )) {
			$query = ' SELECT * FROM #__ja_xml_import_feeds'.
					'  WHERE FeedID = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();
		}
		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->FeedID = null;
			$this->_data->FeedName = null;
			$this->_data->Description = null;
			$this->_data->SampleString = null;
			$this->_data->Method = null;
			$this->_data->FeedURL = null;
			$this->_data->FeedFileName = null;
			$this->_data->FTPUser = null;
			$this->_data->FTPPass = null;
			$this->_data->FTPFileName = null;
			$this->_data->FTPHost = null;
		}
		return $this->_data;
	}
	
	function orderItem($item, $movement){
		$row = &$this->_getTable();
	    $row->load($item);
		if(!$row->move($movement)){			
			$this->setError($row->getError());
			return false;
		}
		return true;
	}	
	
	/**
    * Get field table instance
    * @return JTable Configuration table object
    */
    function &_getTable(){
        if($this->_table == null){
        	$this->_table = &JTable::getInstance('ja_feeds_categories', 'JobBoardTable');
        	
        }
		return $this->_table;
	}
		
	function setOrder($items){
		$str_user_id = implode(',',$items);	
		$total		= count( $items );
		$row		=& $this->_getTable();
		$db = JFactory::getDBO();
		$query = "SELECT id FROM #__ja_feeds_categories WHERE user_id IN ($str_user_id)";
		
		$db->setQuery($query);
		$em_id = $db->loadResultArray();
		
		$order		= JRequest::getVar( 'ordering', array(), 'post', 'array' );
		JArrayHelper::toInteger($order);

		// update ordering values
		for( $i=0; $i < $total; $i++ ) {
			$row->load( $items[$i] );
//			var_dump($order[$i]);exit;
			// track parents
			if ($row->ordering != $order[$i]) {
				$row->ordering = $order[$i];
				if (!$row->store()) {
					$this->setError($row->getError());
					return false;
				}
			} // if
		} // for
		
		return true;
	}
	
	// published categories
	function dopublish( $publish =1, $field='published')
	{
		$db		=& JFactory::getDBO();
		
		$ids = JRequest::getVar('cid', array());
		JArrayHelper::toInteger($cid, array(0));
		$ids = implode( ',', $ids );
		
		if(JRequest::getVar("tab") == "categories")
			$query = "UPDATE #__ja_feeds_categories"
			. "\n SET $field = " . intval( $publish )
			. "\n WHERE id IN ( $ids )"
			;
		else
			$query = "UPDATE #__ja_feeds_items"
			. "\n SET $field = " . intval( $publish )
			. "\n WHERE id IN ( $ids )"
			;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;		
	
	}
	
	function fcnXMLElementOptionsList(&$feed, $selected) {
		$parser = new xmlFeedFieldParser($feed['SampleString']);
		$i=0;
		foreach ($parser->data as $key=>$val) {
			if (strpos($key, $feed['FMD']->seq)!==false) {
				$opt = str_replace($feed['FMD']->seq.'|', '', $key);
				if ($key==$selected) {
					$sel = ' selected ';
				} else {
					$sel = '';
				}
				if($i==0){
					$i++;
					continue;	
				}
				echo '<option style="font-weight:bold" '.$sel.' value="'.htmlentities($key).'">'.htmlentities($opt).'</option>';
			}
		}
		reset ($parser->data);
	}
	
}

// Proccess meta data class

class clsMetaData {
	// Feed identifier
	var $FeedID;
	// Sequence element
	var $seq;
	// Options for each item
	var $options = array();
	// Constructor
	function clsMetaData($feedID) {
		$this->FeedID = $feedID;
	}
	// Get option value
	function getOption($key) {
		if(isset($this->options[$key]))
			return $this->options[$key];
		else 
			return "";
	}
	// Set option value
	function setOption($key, $value) {
		$this->options[$key]=$value;

	}
	// Set sequence element
	function setSequenceElement($elementKey) {
		$this->seq = $elementKey;
	}
	
	// Fill option 
	function fcnFillOptions() {
		$this->setOption('account_create', JRequest::getVar('account_create'));
		$this->setOption('default_user', trim(JRequest::getVar('default_user')));
		$this->setOption('job_identifier', trim(JRequest::getVar('job_identifier')));

		$account_map = array();
		reset($_REQUEST);
		foreach ($_REQUEST as $key=>$val) {
			if (preg_match ('#^ac_#', $key)) {
				$key = str_replace('ac_', '', $key);
				$account_map[$key]['element'] = $val;
			}
		}
		
		$this->setOption('account_map', $account_map);

		// Set password
		$this->setOption('pass_md5', JRequest::getVar('pass_md5'));
		
		$jobMapping = array();
		reset($_REQUEST);
		
		foreach ($_REQUEST as $key=>$val) {
			if (preg_match ('#^xml_element_#', $key)) {
				$key = str_replace('xml_element_', '', $key);
				$jobMapping[$key]['element'] = $val;
				$jobMapping[$key]['code_mode'] = JRequest::getVar('code_mode'.$key);
				$jobMapping[$key]['code_pair'] = JRequest::getVar('code_pair'.$key);
				$jobMapping[$key]['cat_mode'] = JRequest::getVar('cat_mode'.$key);
				$jobMapping[$key]['cat_match'] = JRequest::getVar('cat_match'.$key);
				$jobMapping[$key]['parent_category'] = JRequest::getVar('parent_category'.$key);
				$jobMapping[$key]['parent_category_default'] = JRequest::getVar('parent_category_default'.$key);
				$jobMapping[$key]['validate'] = JRequest::getVar('validate'.$key);
				if (JRequest::getVar('allow_html'.$key)=='') {
					JRequest::setVar('allow_html'.$key, 'N');
				}
				$jobMapping[$key]['allow_html'] = JRequest::getVar('allow_html'.$key);
				$jobMapping[$key]['ignore'] = JRequest::getVar('ignore'.$key);
				$jobMapping[$key]['replace'] = trim(JRequest::getVar('replace'.$key));
			}
		}
		$this->setOption('job_map', $jobMapping);
		reset($_REQUEST);
	}
	
	// Fill data to request
	function fcnFillRequest() {
		// Fill account type
		JRequest::setVar('account_create', $this->getOption('account_create'));
		JRequest::setVar('default_user', $this->getOption('default_user'));
		JRequest::setVar('job_identifier', $this->getOption('job_identifier'));
		JRequest::setVar('job_identifier', $this->getOption('job_identifier'));
		$account_map = array();
		$account_map = $this->getOption('account_map');
		if (is_array($account_map)) {
			foreach ($account_map as $key=>$val) {
				JRequest::setVar('ac_'.$key, $account_map[$key]['element']);
			}
		}
		JRequest::setVar('pass_md5', $this->getOption('pass_md5'));
		JRequest::setVar('app_url', $this->getOption('app_url'));
		JRequest::setVar('guid', $this->getOption('guid'));
		JRequest::setVar('post_mode', $this->getOption('post_mode'));
		JRequest::setVar('post_date', $this->getOption('post_date'));
		
		$jobMapping = array();
		$jobMapping = $this->getOption('job_map');
		if (is_array($jobMapping)) {
			foreach ($jobMapping as $key=>$val) {
				$_REQUEST['xml_element_'.$key] = $jobMapping[$key]['element'];
				$_REQUEST['code_mode'.$key] = $jobMapping[$key]['code_mode'];
				$_REQUEST['code_pair'.$key] = $jobMapping[$key]['code_pair'];
				$_REQUEST['cat_mode'.$key] = $jobMapping[$key]['cat_mode'];
				$_REQUEST['cat_match'.$key] = $jobMapping[$key]['cat_match'];
				$_REQUEST['parent_category'.$key] = $jobMapping[$key]['parent_category'];
				$_REQUEST['parent_category_default'.$key] = $jobMapping[$key]['parent_category_default'];
				$_REQUEST['validate'.$key] = $jobMapping[$key]['validate'];
				$_REQUEST['allow_html'.$key]= $jobMapping[$key]['allow_html'];
				$_REQUEST['ignore'.$key]= $jobMapping[$key]['ignore'];
				$_REQUEST['replace'.$key]= $jobMapping[$key]['replace'];
			}
		}
	}
	
	function save() {
		$db =& JFactory::getDBO();
		$sql = "UPDATE #__ja_xml_import_feeds SET FeedMetaData = '".mysql_real_escape_string(serialize($this))."' WHERE FeedID='".$this->FeedID."' ";
		$db->setQuery($sql);
		
		return $db->query();
	}
}